﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DemoAjaxQuery.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            using (var db = new Models.CATALOG_DBEntities())
            {
                var data = db.Categories.ToList();
                return View(data);
            }
        }

        public ActionResult ProductsInCat(int id)
        {
            using (var db = new Models.CATALOG_DBEntities())
            {
                var qryCat = from it in db.Categories
                             where it.Id == id
                             select it.Name;
                var cat = qryCat.FirstOrDefault();

                ViewData["cat"] = cat;

                var qry = from it in db.Products
                          where it.CategoryId == id
                          select it;
                var data = qry.ToList();

                if (Request.IsAjaxRequest())
                {
                    return PartialView("_ProductsInCat", data);
                }
                return View(data);
            }
        }

        public ActionResult ProductsInCatData(int id)
        {
            using (var db = new Models.CATALOG_DBEntities())
            {
                var qry = from it in db.Products
                          where it.CategoryId == id
                          select new
                          {
                              it.Id,
                              it.Name,
                              it.Description,
                          };
                var data = qry.ToList();
                return Json(data, JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }
    }
}
